<?php

namespace App\Utils\JWTHelper;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class JWTHelper
{
    private static string $alg = 'HS256'; // 算法
    private static string $iss = "imlinnai@163.com";// 签发者
    private static string $aud = "laravel_001"; // 接收者

    /**
     * 创建token
     *
     * @param array $custom 自定义数据
     * @param int $expire 过期时间（单位：分钟）
     * @return string token
     */
    public static function createToken(mixed $custom, int $expire = 8 * 60): string
    {
        $key = env("JWT_KEY");
        $payload = [
            'iss' => self::$iss,
            'aud' => self::$aud,
            'iat' => time(),
            'nbf' => time(),
            'exp' => time() + $expire * 60,
            'custom' => $custom
        ];
        return JWT::encode($payload, $key, self::$alg);
    }

    /**
     * 删除token
     *
     * @return string token
     */
    public static function forgetToken(): string
    {
        return self::createToken([],-60);
    }

    /**
     * 验证token
     *
     * @param string $token token
     * @return bool
     */
    public static function verifyToken(string $token): bool
    {
        $key = env("JWT_KEY");
        try {
            JWT::decode($token, new Key($key, self::$alg));
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    public static function getCustom(string $token): mixed
    {
        $key = env("JWT_KEY");
        try {
            return JWT::decode($token, new Key($key, self::$alg))->custom ?? false;
        }catch (\Exception $e) {
            return false;
        }
    }
}
